package com.zhouzhou.fastjava.query;

import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

public abstract class AbstractLessSubQueryExecutor extends AbstractQueryExecutor {

    public AbstractLessSubQueryExecutor(QueryConfiguration configuration) {
        super(configuration);
    }

    @Override
    protected StringBuilder appendFilterProperties(QueryArgs args, Map<String, QueryField> queryFields, String templateSql, List<Object> params) {
        StringBuilder sqlBuilder = new StringBuilder(templateSql);

        if (args.getFilters() != null && args.getFilters().size() > 0) {
            if (!StringUtils.containsIgnoreCase(templateSql, "where")) {
                sqlBuilder.append(" where ");
            }
            for (QueryFilter filter : args.getFilters()) {
                String filterValue = filter.getValue();
                if (StringUtils.isBlank(filterValue)) {
                    continue;
                }
                String filterName = filter.getName();
                QueryField queryField = getQueryField(queryFields, filterName);
                Object value = getTargetValue(queryField, filterValue);
                if (queryField.isArray()) {
                    throw new QueryException("array mut be static filter");
                } else {
                    sqlBuilder.append(" AND ").append(getQueryFieldSQL(queryField));
                    params.add(value);
                }
            }
        }
        return sqlBuilder;
    }


    @Override
    protected String cleanSql(String sql) {
        String newSql = sql.replaceAll("(?i)(where)\\s+and", "$1");
        newSql = newSql.replaceAll("(?i)(where)\\s+\\)", ")");
        newSql = newSql.replaceAll("(?i)(where)\\s+$", "");
        return newSql;
    }
}
